package com.guigusuqi.commonutils.utils;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;

public class HttpClientUtils
{
    //发起一个get请求，返回数据是以json格式返回
    public static JSONObject doGet(String url) throws IOException
    {
        JSONObject jsonObject = null;

        CloseableHttpClient client = HttpClients.createDefault();

        HttpGet httpGet = new HttpGet(url);
        CloseableHttpResponse response = client.execute(httpGet);
        HttpEntity entity = response.getEntity();

        if(entity != null)
        {
            String result = EntityUtils.toString(entity,"UTF-8");
            jsonObject = JSONObject.parseObject(result);
        }
        httpGet.releaseConnection();;
        return jsonObject;
    }

    //发起一个post请求，返回数据是以json格式返回
    public static String doPost(String url,String jsonParam) throws IOException
    {
        System.out.println(jsonParam);

        // 获取连接客户端工具
        CloseableHttpClient httpClient = HttpClients.createDefault();

        String entityStr = null;
        CloseableHttpResponse response = null;

        try {
            // 创建POST请求对象s
            HttpPost httpPost = new HttpPost(url);
            if (!"".equals(jsonParam)){
                // 创建请求参数
                StringEntity s = new StringEntity(jsonParam, "utf-8");
                //设置参数到请求对象中
                httpPost.setEntity(s);
            }
            //添加请求头信息
            httpPost.addHeader("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.7.6)");
            httpPost.addHeader("Content-Type", "application/json");
            // 执行请求
            response = httpClient.execute(httpPost);
            // 获得响应
            HttpEntity entity = response.getEntity();
            // 将响应结果转换成字符串
            entityStr = EntityUtils.toString(entity, "UTF-8");

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 释放连接
            if (null != response) {
                try {
                    response.close();
                    httpClient.close();
                } catch (IOException e) {
                    System.out.println("释放连接出错");
                    e.printStackTrace();
                }
            }
        }
        // 打印响应内容
        System.out.println("打印响应内容:"+entityStr);
        return entityStr;
    }
}
